package gk.example.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.example.gkdate.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class ImageLoadUtil {
	private static ImageLoadUtil imageLoadUtil;

	private static ImageLoader mImageLoader;
	private static DisplayImageOptions mOptions;
	private static ImageLoaderConfiguration mConfiguration;

	public static ImageLoadUtil getInstance() {
		if (imageLoadUtil == null)
			imageLoadUtil = new ImageLoadUtil();
		return imageLoadUtil;
	}

	/**
	 * 描述: TODO
	 * 
	 * @param context
	 *            :上下文
	 * @param isProgress
	 *            :是否有进度条
	 * @param image
	 *            :被设置的图片
	 * @param uri
	 *            :图片的uri
	 * @param progressBar
	 *            :进度条(没有填null)
	 * @param widthPx
	 *            :图片的宽(默认填0)
	 * @param heigthPx
	 *            : 图片的高(默认填0)
	 * @throws:
	 */
	public synchronized void setImageBackground(Context context,
			boolean isProgress, ImageView image, String uri,
			final ProgressBar progressBar, int widthPx, int heigthPx) {
		if (widthPx != 0 && heigthPx != 0)
			mConfiguration = new ImageLoaderConfiguration.Builder(context)
					.memoryCacheExtraOptions(widthPx, heigthPx).build();
		else
			mConfiguration = ImageLoaderConfiguration.createDefault(context);
		ImageLoader.getInstance().init(mConfiguration);
		mImageLoader = ImageLoader.getInstance();
		mOptions = new DisplayImageOptions.Builder()
				.bitmapConfig(Bitmap.Config.RGB_565)
				.showImageOnLoading(R.drawable.default_round_head)
				.showImageOnFail(R.drawable.default_round_head).cacheOnDisk(true)
				.cacheInMemory(true).build();

		if (isProgress) {
			mImageLoader.displayImage(uri, image, mOptions,
					new SimpleImageLoadingListener(),
					new ImageLoadingProgressListener() {

						@Override
						public void onProgressUpdate(String imageUri,
								View view, int current, int total) {
							// TODO Auto-generated method stub
							progressBar.setProgress((int) Math.round(100.0
									* current / total));
						}
					});
		} else
			
			mImageLoader.displayImage(uri, image, mOptions);
	}

	/**
	 * 描述:清除图片缓存
	 * 
	 * @throws:
	 */
	public void clearCache() {
		try {
			mImageLoader.clearDiskCache();
			mImageLoader.clearMemoryCache();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

